#!/bin/bash
# 部署微信服务 (端口1001)

set -e

echo "开始部署微信服务..."

# 检查是否在项目根目录
if [ ! -d "1-gateway/03-wechat-services" ]; then
    echo "错误: 请在项目根目录执行此脚本"
    exit 1
fi

# 进入微信服务目录
cd 1-gateway/03-wechat-services

# 安装依赖
echo "安装Python依赖..."
pip install -r requirements.txt

# 创建日志目录
mkdir -p ../shared/logs

# 停止旧服务 (如果存在)
echo "停止旧服务..."
pkill -f "gunicorn.*1001" || true
sleep 2

# 启动新服务
echo "启动微信服务 (端口1001)..."
nohup gunicorn -w 2 -b 127.0.0.1:1001 \
    --access-logfile ../shared/logs/wechat-access.log \
    --error-logfile ../shared/logs/wechat-error.log \
    --timeout 60 \
    --daemon \
    wechat_app:app > ../shared/logs/wechat-startup.log 2>&1

# 等待服务启动
sleep 3

# 检查服务状态
if curl -s http://127.0.0.1:1001/api/wechat/health > /dev/null; then
    echo "✅ 微信服务启动成功 (端口1001)"
else
    echo "❌ 微信服务启动失败"
    echo "查看日志: tail -f ../shared/logs/wechat-error.log"
    exit 1
fi

echo "微信服务部署完成"
echo "访问地址: http://127.0.0.1:1001"
echo "日志位置: 1-gateway/shared/logs/"
